<template>
  <div id="user">
    <el-card class="box-card">

<!--      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="userQuery.query" placeholder="请输入内容" clearable @clear="getUserList">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>

      </el-row> -->
<search :query="userQuery" @getList="getUserList">
  <el-col :span="2">
    <el-button type="primary" round @click="addDialogVisible = true">添加用户</el-button>
  </el-col>
</search>

      <!--    表格-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!--修改-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserInfo(scope.row.id)"></el-button>
            <!--删除-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">
            </el-button>
            <!--分配角色-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="rightUserById(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="userQuery.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="userQuery.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="Total">
      </el-pagination>

    </el-card>


    <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="DialogClose('addDialogRef')">
      <el-form label-width="100px" ref="addDialogRef" :rules="addUserRules" :model="addUserForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" @close="DialogClose('editDialogRef')">

      <el-form label-width="100px" ref="editDialogRef" :rules="addUserRules" :model="editUser">
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserClick">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="rightDialogVisible" @close="value=''">
      <p>用户名称:{{rightUser.username}}</p>
      <p>用户角色:{{rightUser.role_name}}</p>
      
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in rightList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
        
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightDialogClick">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
  import search from "@/component/search.vue"
  import {
    remove
  } from "@/network/remove";
  import {
    addInfo
  } from "@/network/add";

  export default {
    data() {
      return {
        addUserForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        addUserRules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
         },  ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
              message: '邮箱格式不对',
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
            {
              pattern: /^0{0,1}(13[0-9]|15[7-9]|153|156|18[0-9])[0-9]{8}$/,
              message: '手机号格式不对',
              trigger: 'blur'
            }
          ]
        },
        userQuery: {
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        userList: [],
        Total: 0,
        //添加用户对话框
        addDialogVisible: false,
        //修改用户信息对话框
        editDialogVisible: false,
        // 分配角色对话框
        rightDialogVisible: false,
        // 当前角色信息
        rightUser:{},
        // 选择角色列表
        rightList:[],

        editUser: {},
// 选择的角色
        value: '',
      }
    },
    components:{
      search
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        const {
          data: res
        } = await this.$http.get('users', {
          params: this.userQuery
        })
        if (res.meta.status != 200) return this.$message.error(res.meta.msg)
        console.log(res);
        this.userList = res.data.users
        this.Total = res.data.total
      },
      handleSizeChange(newSizi) {
        console.log(newSizi)
        this.userQuery.pagesize = newSizi
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        console.log(newPage)
        this.userQuery.pagenum = newPage
        this.getUserList()
      },
      async userStateChanged(userInfo) {
        const {
          data: res
        } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status != 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$Message.error("更新用户状态失败")
        }
        this.$Message.success('更新用户状态成功')
      },
      DialogClose(ref) {
        this.$refs[ref].resetFields()
      },

      addUser() {
        this.addInfo(this.$refs.addDialogRef, 'users', this.addUserForm, this.addDialogVisible = false, this
          .getUserList)
      },
      async editUserInfo(id) {
        const {
          data: res
        } = await this.$http.get(`users/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$Message.error("修改失败")
        this.editDialogVisible = true
        this.editUser = res.data
      },
    async rightUserById(row) {
        this.rightUser = row
        this.rightDialogVisible = true
        const {data: res} = await this.$http.get(`roles`)
        // console.log(res)
        if (res.meta.status !== 200) return this.$Message.error("获取列表失败")
        this.rightList = res.data
        
        // console.log(res);
      },
      async rightDialogClick(){
        if(!this.value) return this.$Message.error("请选择角色")
        const {
          data: res
        } = await this.$http.put(`users/${this.rightUser.id}/role`, {
          rid: this.value,
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$Message.error("修改用户失败")
        this.$Message.success("修改用户成功")
        this.getUserList()
        this.rightDialogVisible =false
      },
      editUserClick() {
        this.$refs.editDialogRef.validate(async valid => {
          if (!valid) return
          const {
            data: res
          } = await this.$http.put(`users/${this.editUser.id}`, {
            email: this.editUser.email,
            mobile: this.editUser.mobile
          })
          // console.log(res)
          if (res.meta.status !== 200) return this.$Message.error("修改用户失败")
          this.$Message.success("修改用户成功")

          this.editDialogVisible = false
          this.getUserList()
        })
      },
      removeUserById(id) {
        remove(`users/${id}`, this.getUserList)
      }

    },

  }
</script>

<style lang="less" scoped>
  .el-row {
    margin-bottom: 15px;
  }
</style>
